package com.corejsf;

import java.io.Serializable;
import java.util.ArrayList;

import javax.inject.Inject;
import javax.inject.Named; 
   // or import javax.faces.bean.ManagedBean;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped; 
   // or import javax.faces.bean.SessionScoped;

@Named
@SessionScoped
/**
 * Menu only available to the superUser. Allows the superUser to add,
 * modify, create and delete users.
 * @author Jitin Dhillon, Kelton Kowalchuk
 *
 */
public class SuperMenu implements Serializable {
    /**
     * Login bean.
     */
    @Inject Login login;
    @Inject Credentials credentials;
    private ArrayList<User> temp = credentials.users;
    
    /**
     * Will set the activeUser to null and reset password and 
     * username fields.
     * @return navigation to the login page.
     */
    public String logout(){
		login.setActiveUser(null);
		login.setPassword("");
		login.setPassword("");
		login.getConversation().end();
		return "login?faces-redirect=true";
	}
    /**
     * Will delete a user from the system.
     * @param user user to delete.
     */
	public void delete(User user){
		if(!user.isSuperUser()){
		temp.remove(user);
		}
	}
	/**
	 * Adds a user to the system.
	 */
	public String add(){
		if(!login.getActiveUser().isSuperUser()){
			login.setActiveUser(null);
			login.setPassword("");
			login.setPassword("");
			return "login?faces-redirect=true";
	       }
		
		User user = new User("", "", "" , 1);
		user.setEditable(true);
		temp.add(user);
		return "superMenu";
	}
	/**
	 * Save the changes made to the users list.
	 */
	public void save() {
	      for (User u : temp){
	    	  u.setEditable(false);
	      }
	      login.credentials.users = temp;
	   }

    public ArrayList<User> getTemp() {
		return temp;
	}

	public void setTemp(ArrayList<User> temp) {
		this.temp = temp;
	}

	public ArrayList<User> getCredentials() {
		return login.credentials.users;
	}

	public void setCredentials(Credentials credentials) {
		this.login.credentials.users = login.credentials.users;
	}
	
	SuperMenu() {
       checkUser();
    }
	
	String checkUser(){
		if(!login.getActiveUser().isSuperUser()){
	    	   return "login";
	       }
		else return "superMenu";
	}
	public Login getLogin() {
		return login;
	}
	public void setLogin(Login login) {
		this.login = login;
	}

}